package com.nari.ncps.screen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.common.pojo.ApiResponse;
import com.nari.ncps.screen.entity.ConfigDatasourceInfo;
import com.nari.ncps.screen.mapper.ConfigDatasourceInfoMapper;
import com.nari.ncps.screen.service.ConfigDatasourceInfoService;
import com.nari.ncps.screen.utils.DataSourceSwitchEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 环境信息表 服务实现类
 * </p>
 *
 * @author dongxiaoxu
 * @since 2025-10-15
 */
@Service
@Slf4j
public class ConfigDatasourceInfoServiceImpl extends ServiceImpl<ConfigDatasourceInfoMapper, ConfigDatasourceInfo>
        implements ConfigDatasourceInfoService {

    @Autowired
    private ApplicationEventPublisher eventPublisher;


    @Override
    public ApiResponse<Object> switchDs(boolean enable) {
        // 第一步：将所有数据源状态设置为0
        LambdaUpdateWrapper<ConfigDatasourceInfo> disableWrapper = new LambdaUpdateWrapper<>();
        disableWrapper.set(ConfigDatasourceInfo::getDsStatus, 0);
        baseMapper.update(null, disableWrapper);

        // 第二步：启用指定数据源
        LambdaUpdateWrapper<ConfigDatasourceInfo> enableWrapper = new LambdaUpdateWrapper<>();
        if (enable) {
            enableWrapper.eq(ConfigDatasourceInfo::getDsName, "primary")
                    .set(ConfigDatasourceInfo::getDsStatus, 1);
            log.info("数据源已切换到主数据源(primary)");
        } else {
            enableWrapper.eq(ConfigDatasourceInfo::getDsName, "secondary")
                    .set(ConfigDatasourceInfo::getDsStatus, 1);
            log.info("数据源已切换到应急数据源(secondary)");
        }
        baseMapper.update(null, enableWrapper);

        // 发布数据源切换事件
        eventPublisher.publishEvent(new DataSourceSwitchEvent(this));


        return ApiResponse.succeed("数据源切换成功");
    }

    @Override
    public ApiResponse<ConfigDatasourceInfo> currentDs() {

        LambdaQueryWrapper<ConfigDatasourceInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ConfigDatasourceInfo::getDsStatus,1);
        ConfigDatasourceInfo one = this.getOne(lqw);
        return ApiResponse.succeed(one);
    }


}
